import { defineStore } from 'pinia'
import { ref } from 'vue'

export type ThemeMode = 'light' | 'dark' | 'auto'

export const useThemeStore = defineStore('theme', () => {
  // 主题模式
  const mode = ref<ThemeMode>('light')
  
  // 是否为暗色主题
  const isDark = ref(false)

  // 初始化主题
  const initTheme = () => {
    const savedMode = localStorage.getItem('theme-mode') as ThemeMode
    if (savedMode && ['light', 'dark', 'auto'].includes(savedMode)) {
      mode.value = savedMode
    } else {
      // 默认跟随系统
      mode.value = 'auto'
    }
    applyTheme()
  }

  // 应用主题
  const applyTheme = () => {
    const html = document.documentElement
    
    if (mode.value === 'auto') {
      // 跟随系统主题
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)')
      isDark.value = mediaQuery.matches
      
      // 监听系统主题变化
      mediaQuery.addEventListener('change', (e) => {
        if (mode.value === 'auto') {
          isDark.value = e.matches
          updateDocumentTheme()
        }
      })
    } else {
      isDark.value = mode.value === 'dark'
    }
    
    updateDocumentTheme()
  }

  // 更新文档主题类名
  const updateDocumentTheme = () => {
    const html = document.documentElement
    
    if (isDark.value) {
      html.classList.add('dark')
      html.classList.remove('light')
    } else {
      html.classList.add('light')
      html.classList.remove('dark')
    }
  }

  // 切换主题模式
  const setThemeMode = (newMode: ThemeMode) => {
    mode.value = newMode
    localStorage.setItem('theme-mode', newMode)
    applyTheme()
  }

  // 切换亮色/暗色
  const toggleTheme = () => {
    const newMode = isDark.value ? 'light' : 'dark'
    setThemeMode(newMode)
  }

  return {
    mode,
    isDark,
    initTheme,
    setThemeMode,
    toggleTheme
  }
}) 